<?php
class tls_func {


	static function week2day($week, $year) {

//		$week = substr($wtime, 4);
		$timestamp = mktime(0,0,0,1,1,$year);
       	$dayofweek = date("w",$timestamp);
       	if( $week != 1)
       		$distance = ($week-1)*7-$dayofweek+1;

       	$passed_seconds = $distance * 86400;
        $timestamp += $passed_seconds;
      	$firt_date_of_week = $timestamp; // date("Ymd",$timestamp);
      	if($week == 1)
      		$distance = 7-$dayofweek;
       	else
       		$distance = 6;
      	$timestamp += $distance * 86400;
     	$last_date_of_week = $timestamp; // date("Ymd",$timestamp);

     	return array($firt_date_of_week,$last_date_of_week);
	}

	/**
	 * 远程rest交互
	 * @param unknown_type $http_method
	 * @param unknown_type $url
	 * @param unknown_type $extra_headers
	 * @param unknown_type $post_data
	 * @param unknown_type $return_response_headers
	 * @param unknown_type $use_json_format
	 */
	static function rest_request_autobuildpostdata($http_method, $url, $extra_headers=null, $post_data=null, $return_response_headers=true, $use_json_format = true) {
		return tls_func::rest_request($http_method, $url, $extra_headers, http_build_query($post_data), $return_response_headers, $use_json_format);
	}
	static function rest_request($http_method, $url, $extra_headers=null, $post_data=null, $return_response_headers=true, $use_json_format = true, $timeout = 30) {
		$curl = curl_init($url);
		curl_setopt($curl, CURLOPT_RETURNTRANSFER, true);
		curl_setopt($curl, CURLOPT_FAILONERROR, false);
		curl_setopt($curl, CURLOPT_SSL_VERIFYPEER, false);
	    curl_setopt($curl, CURLOPT_CONNECTTIMEOUT, $timeout);
	    curl_setopt($curl, CURLOPT_TIMEOUT, $timeout);

		curl_setopt($curl, CURLINFO_HEADER_OUT, true);

		if ($return_response_headers) curl_setopt($curl, CURLOPT_HEADER, true);

		$headers = array();
		if (is_array($extra_headers)) $headers = array_merge($headers, $extra_headers);

		$http_method = strtoupper($http_method);
		switch($http_method) {
			case 'GET':
				curl_setopt($curl, CURLOPT_HTTPHEADER, $headers);
				break;
			case 'POST':
		        curl_setopt($curl, CURLOPT_HTTPHEADER, $headers);
		        curl_setopt($curl, CURLOPT_POST, true);
		        curl_setopt($curl, CURLOPT_POSTFIELDS, $post_data);
		        break;
    		case 'PUT':
		      	$headers[] = 'If-Match: *';
		      	curl_setopt($curl, CURLOPT_HTTPHEADER, $headers);
		      	curl_setopt($curl, CURLOPT_CUSTOMREQUEST, $http_method);
		      	curl_setopt($curl, CURLOPT_POSTFIELDS, $post_data);
		      	break;
    		case 'DELETE':
		      	$headers[] = 'If-Match: *';
		      	curl_setopt($curl, CURLOPT_HTTPHEADER, $headers);
		      	curl_setopt($curl, CURLOPT_CUSTOMREQUEST, $http_method);
		      	break;
    		default:
      			curl_setopt($curl, CURLOPT_HTTPHEADER, $headers);
  		}

  		$response = curl_exec($curl);
  		if (!$response) $response = curl_error($curl);

  		$data = curl_getinfo($curl, CURLINFO_HEADER_OUT) . $response;

  		curl_close($curl);
//var_dump($data);
  		$response_header = $response = null;
		list($request_header, $response_header, $response) = array_pad(explode("\r\n\r\n", $data, 4), 4, null);

		if(!$return_response_headers) {
			$response = $response_header;
			$response_header = null;
		}
		return array(
			'request_header' => $request_header,
			'response_header' => $response_header,
			'data' => empty($response) ? array() : ($use_json_format ? json_decode($response, true) : $response),
			'request_data' => $post_data
		);
	}


	static function get_http_referer() {
		if(isset($_SERVER['HTTP_REFERER'])) {
			$http_ref = parse_url($_SERVER['HTTP_REFERER']);
			$http_ref_query = array();
			isset($http_ref['query']) && parse_str($http_ref['query'], $http_ref_query);
			$http_ref['query'] = $http_ref_query;
		} else {
			$http_ref = array();
		}
		return $http_ref;
	}


	static function redirect($url, $type = 'html') {
		switch($type) {
		case 'html':
			echo '<meta http-equiv="refresh" content="0;url=' . $url . '">';
			break;
		case 'js':
			echo '<script type="text/javascript">top.location.replace("' . $url . '");</script>';
			break;
		}

		exit;
	}

	public static function xdump() {
		$tmp = func_get_args();
		echo '<pre>';
		foreach($tmp as $arg) {
			var_dump($arg);
//			print_r($arg);
		}
		echo '</pre>';
	}

	public static function escape( $string){
		return mysql_escape_string( trim($string));
	}

	/**
	 * 正整型
	 */
	public static function uint($num){
		return max(0, (int)$num);
	}

	public static function day_left($d_time) {
		$d_time = (int)$d_time;
		if(0 == $d_time || $d_time > NOW) return '';

		$x_time = (NOW - $d_time)/3600*60;
		$s_time = '';
		if ($x_time >= 60){ // 小時計
			$x_time = (NOW - $d_time)/3600;
			if ($x_time >= 24){
				if ($x_time < 120){ // 5天內
					$x_time = $x_time/24;
					switch($x_time) {
						case 1:
							$s_time = '昨天';
							break;
						case 2:
							$s_time = '前天';
							break;
						default:
							$s_time = (int) $x_time . '天前';
					}
				} else {
					$s_time = date('m月d日', $d_time);
				}
			} else {
				$s_time = (int) $x_time  . '小時前';
			}
		}else{
			switch(true) {
				case ($x_time < 5):
					$s_time = '剛剛';
					break;
				default:
					$s_time = (int) $x_time . '分鐘前';
			}
		}
		return $s_time;
	}

	/**
     * 根据设定的概率数组, 随机产生一个概率对应的键
     * @access private
     * @param array $all_randoms array(5, 15, 20, 30, 30),每个数组元素值必须为正整数,可以重复
     * @return mixed 概率值对应的键
     */
    public static function gen_random($all_randoms=array()) {
    	$probabilitySum = array_sum($all_randoms);//概率数组的总概率精度
    	$result = '';

    	foreach ($all_randoms as $key=>$probability) {
    		$random = mt_rand(1, $probabilitySum);
    		if ($random <= $probability) {
    			$result = $key;
    			break;
    		} else {
    			$probabilitySum -= $probability;
    		}
    	}

    	return $result;
    }
    
	/**
     * 返回浏览器信信息.ver为版本号,nav为浏览器
	 */
	public static function getbrowser(){
		$browsers = "mozilla msie gecko firefox ";
		$browsers.= "konqueror safari netscape navigator ";
		$browsers.= "opera mosaic lynx amaya omniweb";
		$browsers = preg_split("/\s+/", $browsers);
		$nua = strtolower( $_SERVER['HTTP_USER_AGENT']);
		$l = strlen($nua);
		for ($i=0; $i<count($browsers); $i++){
			$browser = $browsers[$i];
			$n = stristr($nua, $browser);
			if(strlen($n)>0){
				$aInfo["ver"] = "";
				$aInfo["nav"] = $browser;
				$j=strpos($nua, $aInfo["nav"])+$n+strlen($aInfo["nav"])+1;
				for (; $j<=$l; $j++){
					$s = substr ($nua, $j, 1);
					if(is_numeric($aInfo["ver"].$s) )
					$aInfo["ver"] .= $s;
					else
					break;
				}
			}
		}
		
		return $aInfo;
	}  
	/**
	 * 获得用户所使用的操作系统
	 *
	 * @return string 用户的操作系统的简称
	 */
	public static function getsys() {
		$os = $_SERVER["HTTP_USER_AGENT"];// 浏览者操作系统及浏览器
	
		// 分析操作系统
		if(strpos($os,"Windows NT 5.0")) $os="windows2000";
		elseif(strpos($os,"Windows NT 6.1")) $os="windows7";
		elseif(strpos($os,"Windows NT 6.0")) $os="windowsvista";
		elseif(strpos($os,"Windows NT 5.1")) $os="windowsxp";
		elseif(strpos($os,"Windows NT 5.2")) $os="windows2003";
		elseif(strpos($os,"Windows NT")) $os="windowsnt";
		elseif(strpos($os,"Windows 9")) $os="windows98";
		elseif(strpos($os,"unix")) $os="unix";
		elseif(strpos($os,"linux")) $os="linux";
		elseif(strpos($os,"SunOS")) $os="sunos";
		elseif(strpos($os,"BSD")) $os="freebsd";
		elseif(strpos($os,"Mac")) $os="mac";
		else $os="other";
		
		return $os;
	}
	
	/**
	 * 
	 * 邮件发送方法 直接使用socket方式发送
	 * @param unknown_type $mnick
	 * @param array $strMails
	 * @param unknown_type $strSubject
	 * @param unknown_type $strMsg
	 * @param array $opt
	 * 		MAIL_SERVER,
	 * 		MAIL_PORT,
	 * 		MAIL_AUTH,
	 * 		MAIL_USER,
	 * 		MAIL_PASSWORD
	 * 		MAIL_FROM
	 * @return number|string|boolean
	 */
	public static function sendmail($mnick, $strMails, $strSubject, $strMsg, $opt){
		
//define( 'MAIL_SERVER', '221.194.129.91');			//SMTP服务器地址 GMAIL 为:  ssl://smtp.gmail.com:465     smtp.126.com
//define( 'MAIL_PORT', 25); 							//服务器端口
//define( 'MAIL_AUTH', true); 						//smtp服务器是否需要验证
//define( 'MAIL_USER', 'antwars@mail.boyapoker.com'); //SMTP用户名   zjstandup@126.com   boyaagame@126.com
//define( 'MAIL_PASSWORD', 'ant4553sraw'); 			//密码    zhoujian    boyainfo
//define( 'MAIL_FROM', 'antwars@mail.boyapoker.com'); //回复邮箱地址,126的强制跟MAIL_USER相同,gmail的可以不同
//define( 'MAIL_MNICK', '博雅互动'); 					//发送者名字
		
		$opt['MAIL_MNICK'] = $mnick;
		foreach ( explode( ',', $strMails) as $touser ) {
			$tousers[] = preg_match( '/^(.+?) \<(.+?)\>$/', $touser, $to) ? ($opt['MAIL_MNICK'] ? '=?utf-8?B?' . base64_encode( $to[1]) . "?= <$to[2]>" : $to[2]) : $touser;
		}
		$strHeader = "From: " . $opt['MAIL_FROM'] . "\r\nX-Priority: 3\r\nX-Mailer: BOYAA!\r\nMIME-Version: 1.0\r\nContent-type: text/html; charset=UTF-8\r\nContent-Transfer-Encoding: base64\r\n";
		$strHeader .= 'Message-ID: <' . gmdate( 'YmdHs') . '.' . substr( md5( $strMsg . microtime()), 0, 6) . rand( 100000, 999999) . '@' . $_SERVER['HTTP_HOST'] . ">\r\n";
		$strMails = implode( ',', $tousers);
		$strSubject = '=?utf-8?B?' . base64_encode( str_replace( "\r", '', str_replace( "\n", '', '[' . $opt['MAIL_MNICK'] . '] ' . $strSubject))) . '?=';
		$strMsg = chunk_split( base64_encode( str_replace( "\r\n.", " \r\n..", str_replace( "\n", "\r\n", str_replace( "\r", "\n", str_replace( "\r\n", "\n", str_replace( "\n\r", "\r", $strMsg)))))));
		
		if (!$fp = fsockopen( $opt['MAIL_SERVER'], $opt['MAIL_PORT'], $errno, $errstr, 30)) {
			return 1000;
		}
		stream_set_blocking( $fp, true);
		$lastmessage = fgets( $fp, 512);
		if (substr( $lastmessage, 0, 3) != '220') {
			return $lastmessage;
		}
		fputs( $fp, ($auth ? 'EHLO' : 'HELO') . " boyaa\r\n");
		$lastmessage = fgets( $fp, 512);
		if (substr( $lastmessage, 0, 3) != 220 && substr( $lastmessage, 0, 3) != 250) {
			return $lastmessage;
		}
		
		while ( 1 ) {
			if (substr( $lastmessage, 3, 1) != '-' || empty( $lastmessage)) {
				break;
			}
			$lastmessage = fgets( $fp, 512);
		}
		
		if ($opt['MAIL_AUTH']) {
			fputs( $fp, "AUTH LOGIN\r\n");
			$lastmessage = fgets( $fp, 512);
			if (substr( $lastmessage, 0, 3) != 334) {
				return $lastmessage;
			}
			fputs( $fp, base64_encode( $opt['MAIL_USER']) . "\r\n");
			$lastmessage = fgets( $fp, 512);
			if (substr( $lastmessage, 0, 3) != 334) {
				return $lastmessage;
			}
			
			fputs( $fp, base64_encode( $opt['MAIL_PASSWORD']) . "\r\n");
			$lastmessage = fgets( $fp, 512);
			if (substr( $lastmessage, 0, 3) != 235) {
				return $lastmessage;
			}
		}
		
		fputs( $fp, "MAIL FROM: <" . preg_replace( "/.*\<(.+?)\>.*/", "\\1", $opt['MAIL_FROM']) . ">\r\n");
		$lastmessage = fgets( $fp, 512);
		if (substr( $lastmessage, 0, 3) != 250) {
			fputs( $fp, "MAIL FROM: <" . preg_replace( "/.*\<(.+?)\>.*/", "\\1", $opt['MAIL_FROM']) . ">\r\n");
			$lastmessage = fgets( $fp, 512);
			if (substr( $lastmessage, 0, 3) != 250) {
				return $lastmessage;
			}
		}
		
		$email_tos = array();
		foreach ( explode( ',', $strMails) as $touser ) {
			$touser = trim( $touser);
			if ($touser) {
				fputs( $fp, "RCPT TO: <" . preg_replace( "/.*\<(.+?)\>.*/", "\\1", $touser) . ">\r\n");
				$lastmessage = fgets( $fp, 512);
				if (substr( $lastmessage, 0, 3) != 250) {
					fputs( $fp, "RCPT TO: <" . preg_replace( "/.*\<(.+?)\>.*/", "\\1", $touser) . ">\r\n");
					$lastmessage = fgets( $fp, 512);
					return $lastmessage;
				}
			}
		}
		
		fputs( $fp, "DATA\r\n");
		$lastmessage = fgets( $fp, 512);
		if (substr( $lastmessage, 0, 3) != 354) {
			return $lastmessage;
		}
		
		fputs( $fp, "Date: " . gmdate( 'r') . "\r\n");
		fputs( $fp, "To: " . $strMails . "\r\n");
		fputs( $fp, "Subject: " . $strSubject . "\r\n");
		fputs( $fp, $strHeader . "\r\n");
		fputs( $fp, "\r\n\r\n");
		fputs( $fp, "$strMsg\r\n.\r\n");
		$lastmessage = fgets( $fp, 512);
		if (substr( $lastmessage, 0, 3) != 250) {
			return $lastmessage;
		}
		
		fputs( $fp, "QUIT\r\n");
		return true;
	}
	
	
	/**
	 * 设置cookies
	 * Enter description here ...
	 * @param unknown_type $name
	 * @param unknown_type $value
	 * @param unknown_type $time
	 */
	static public function setCookie($name, $value, $time=0){
	    $expires = $time ? self::time()+(int)$time : 0;
	    setcookie($name, $value, $expires, '/');
    } 
 
    /**
     * 返回UNIX时间   
     * @param boolen $float 是否精确到微�?     
     * @return int/float
     */
	static function time( $float=false){
		return $float ? microtime( true) : time();
	}
	
	
	/**
	 * 返回到第二天七点的时间差（秒）
	 * 若在午夜，就返回到当天七点的时间差
	 */
	static public function timeToSeven() {
		$whichDay = (int)date("G")>7?strtotime("tomorrow"):strtotime("today");
		return $tomorrowSevenClock = strtotime("7 hours",$whichDay)-NOW;
	}
	
	/**
	 * 页面接受信息加转义 
	 * 小菜
	 * 2011/05/06
	 */
	static public function my_addslashes($string, $force = 0, $strip = FALSE) {
		if (! get_magic_quotes_gpc() || $force) {
			if (is_array ( $string )) {
				foreach ( $string as $key => $val ) {
					$string [$key] = my_addslashes ( $val, $force, $strip );
				}
			} else {
				$string = addslashes ( $strip ? stripslashes ( trim ( $string ) ) : trim ( $string ) );
			}
		}
		return $string;
	}
	
	/**
	 * 显示提示，并跳转 
	 * 小菜(魏翠霞)
	 * 2011/05/06
	 */
	static public function showmessage($show_message, $url_forward = '', $waitting = '1') {
		$message = $show_message;
		if ($waitting > 0) {
            $script_func = 'window.location.href =\'' . $url_forward . '\';';

            if($url_forward == "refresh"){
                $script_func = 'window.location.replace(window.location.href);';
            }
            $location = $url_forward;
		}else{
            @header("Location:".$url_forward);
            exit;
        }
        
        $webUrl = ujn::getCFG('urls.static');
        
        include_once ujn::getCFG('templates_component_path').'showmessage.php';
		exit ();
	}
	
	
	
	//取扩展名
	static public function getExt($filename)
	{
		return strtolower(substr(strrchr($filename, '.'), 0));
	}
	
	/**
	 * 上传图片
	 * @author 小菜(魏翠霞)
	 * @date 2011/05/09
	 */
	static public function uploadpic($file, $dstfile = '', $filesize = 0)
	{
		$extension = tls_func::getExt($file['name']);
		if(!is_dir(dirname($dstfile))) mkdir(dirname($dstfile), 0777, true);
		if(!empty($filesize) && $file['size'] > $filesize * 1024 ){
			return '-1';
		}
		if(strpos(".gif.jpg.png.jpeg", $extension) === false){
			return '-2';
		}
		if(move_uploaded_file($file['tmp_name'], $dstfile)){
			Return $dstfile;
		}
		elseif(copy($file['tmp_name'], $dstfile)){
			Return $dstfile;
		}else{
			return false;
		}	
	}
	
	/**
	 * 得到一个SQL语句
	 * @param array  $data 要插入的数组
	 * @param string $table 表名
	 * @param string $construct 是否插入或者删除
	 * @param array  $clear 不构造项 (已删)
	 * @return $sql
	 * @author 小菜(魏翠霞)
	 * @date 2011/05/09
	 */
	function ConvSql($data, $table = '', $construct = 'INSERT')
	{
		$sqlArr = array();
		if(empty($data) || !is_array($data)) return '';
		foreach($data as $key=>$val) {
			$sqlArr[] = "`".$key."` = '".($val)."'";
		}
		$sql = implode(",", $sqlArr);
		if(empty($table)) return $sql;
		if($construct == 'INSERT') return "INSERT INTO `".$table."` SET ".$sql;
		if($construct == 'UPDATE')  return "UPDATE `".$table."` SET ".$sql;
		if($construct == 'REPLACE')  return "REPLACE INTO `".$table."` SET ".$sql;

	}
	
	//得到访问者IP
	function getonlineip() {
	
		if (getenv ( 'HTTP_CLIENT_IP' ) && strcasecmp ( getenv ( 'HTTP_CLIENT_IP' ), 'unknown' )) {
			$onlineip = getenv ( 'HTTP_CLIENT_IP' );
		} elseif (getenv ( 'HTTP_X_FORWARDED_FOR' ) && strcasecmp ( getenv ( 'HTTP_X_FORWARDED_FOR' ), 'unknown' )) {
			$onlineip = getenv ( 'HTTP_X_FORWARDED_FOR' );
		} elseif (getenv ( 'REMOTE_ADDR' ) && strcasecmp ( getenv ( 'REMOTE_ADDR' ), 'unknown' )) {
			$onlineip = getenv ( 'REMOTE_ADDR' );
		} elseif (isset ( $_SERVER ['REMOTE_ADDR'] ) && $_SERVER ['REMOTE_ADDR'] && strcasecmp ( $_SERVER ['REMOTE_ADDR'], 'unknown' )) {
			$onlineip = $_SERVER ['REMOTE_ADDR'];
		}
		preg_match ( "/[\d\.]{7,15}/", $onlineip, $onlineipmatches );
		$onlineip = $onlineipmatches [0] ? $onlineipmatches [0] : 'unknown';
	
		return $onlineip;
	}
	
	//自动截图函数
	function userCutPic($bigImage,$txt_Zoom,$txt_left,$txt_top,$uid)
	{
	
		$targ_w = $targ_h = 120;
		$jpeg_quality = 100;
	
		$src = $bigImage; //原大图
		$src_ext = explode('.',$src);
		$_src_ext = $src_ext[3]; //图片后缀
		
		switch ($_src_ext) {
			case "gif":
				$img_r = @imagecreatefromgif($src);
				break;
			case "jpeg":
				$img_r = @imagecreatefromjpeg($src);
				break;
			case "jpg":
				$img_r = @imagecreatefromjpeg($src);
				break;
			case "png":
				$img_r = @imagecreatefrompng($src);
				break;
			default:
				$img_r = @imagecreatefromjpeg($src);
				break;
		}
		
		$dst_r = ImageCreateTrueColor( $targ_w, $targ_h );
		
		$x = $targ_h/$txt_Zoom;
		
		@imagecopyresampled($dst_r,$img_r,0,0,$txt_left/$txt_Zoom,$txt_top/$txt_Zoom,$targ_w,$targ_h,$x,$x);
		$uploadfile = ujn::getCFG('paths.uicons').'small/'.$uid.'.jpg';
		if(!is_dir(dirname($uploadfile))) mkdir(dirname($uploadfile), 0777, true);
		
		switch ($_src_ext) {
			case "gif":
				imagegif($dst_r, $uploadfile);
				break;
			case "jpeg":
				imagejpeg($dst_r, $uploadfile);
				break;
			case "jpg":
				imagejpeg($dst_r, $uploadfile);
				break;
			case "png":
				imagepng($dst_r, $uploadfile);
				break;
			default:
				imagejpeg($dst_r, $uploadfile);
				break;
		}
		
		return true;
	}
	
	//删除文件目录下所有文件
	function delDir($dirName) {
	  if ( $handle = opendir( "$dirName" ) ) {
		   while ( false !== ( $item = readdir( $handle ) ) ) {
		   	if ( $item != "." && $item != ".." ) {
			   	if ( is_dir( "$dirName/$item" ) ) {
			   		tls_func::delDir( "$dirName/$item" );
			   	} else {
			   		if( unlink( "$dirName/$item" ) ) return true; //echo "成功删除文件： $dirName/$item<br />\n";
			   	}
		   	}
		  }
		closedir( $handle );
   		if( rmdir( $dirName ) ) return true; //echo "成功删除目录： $dirName<br />\n";
	   }
	}
	
	//curl
	function makeRequest($url, $params, $ch=null, $is_post = false) {
	    if (!$ch)
	      $ch = curl_init();
	
	    $opts = array(
	    	CURLOPT_CONNECTTIMEOUT	=> 10,
	    	CURLOPT_RETURNTRANSFER	=> true,
	    	CURLOPT_TIMEOUT       				=> 60,
	    	CURLOPT_USERAGENT      			=> '266-php-0.1',
	    );
	    if ($is_post) {
	      $opts[CURLOPT_POSTFIELDS] = http_build_query($params, null, '&');
	    } else {
	    	$url .= '&' . http_build_query($params, null, '&');
	    }
	    $opts[CURLOPT_URL] = $url;
	
	    if (isset($opts[CURLOPT_HTTPHEADER])) {
	      $existing_headers = $opts[CURLOPT_HTTPHEADER];
	      $existing_headers[] = 'Expect:';
	      $opts[CURLOPT_HTTPHEADER] = $existing_headers;
	    } else {
	      $opts[CURLOPT_HTTPHEADER] = array('Expect:');
	    }
	
	    curl_setopt_array($ch, $opts);
	    $result = curl_exec($ch);
	
	    if (curl_errno($ch) == 60) { // CURLE_SSL_CACERT
	      throw new Exception('CURLE_SSL_CACERT');
	    }
	
	    if ($result === false) {
	      curl_close($ch);
	      throw new Exception('CurlException');
	    }
	    curl_close($ch);
	    return $result;
	}
	

    
}